package top.smallway.lightbandassistant_app.UI;

import static top.smallway.lightbandassistant_app.method.Method.unmarshalSongDataList;
import static top.smallway.lightbandassistant_app.method.Method.unmarshalSongData;
import static top.smallway.lightbandassistant_app.method.Method.checkAndExtract;
import static top.smallway.lightbandassistant_app.method.Method.extract;
import static top.smallway.lightbandassistant_app.method.Method.secondsToTimeFormat;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson2.JSONArray;
import com.google.android.material.search.SearchBar;
import com.google.android.material.search.SearchView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import top.smallway.lightbandassistant_app.R;
import top.smallway.lightbandassistant_app.UI.type.FindMessageType;
import top.smallway.lightbandassistant_app.adapter.SongsAdapter;
import top.smallway.lightbandassistant_app.adapter.WordsAdapter;
import top.smallway.lightbandassistant_app.data.Song_Data;
import top.smallway.lightbandassistant_app.network.Okhttp;
import top.smallway.lightbandassistant_app.network.Search;

/**
 * 发现页面Fragment
 * 负责实现歌曲搜索、展示和预览功能
 */
public class Find extends Fragment {
    // 歌曲数据列表
    private List<Song_Data> Songs;
    // 播放器状态常量
    private final int PLAYER_PLAYING = 0;
    private final int PLAYER_STOP = 1;
    // 节点常量
    private final int SINGGAPORE_NODE = 0;

    private final int MAX_NPS = 200; // 20 should be large enough

    // 搜索栏和搜索视图
    private SearchBar searchBar;
    private SearchView searchView;
    private ImageButton advancedButton;
    private LinearLayout linearLayout;

    private float minNps = 0.0f;
    private float maxNps = MAX_NPS;

    private SeekBar minNpsSeekBar;
    private SeekBar maxNpsSeekBar;

    private TextView npsText;
    private Button searchBtn;

    // 当前节点
    private int node;
    // 播放器当前状态
    private final int PLAYER_STATIC = PLAYER_STOP;

    // 歌曲列表和搜索建议列表的RecyclerView
    private RecyclerView songs, words_recycler;
    // 搜索功能实例
    private Search search1;
    // 网格布局管理器
    private GridLayoutManager gridLayoutManager;
    // 歌曲列表和搜索建议的适配器
    private SongsAdapter songsAdapter;
    private WordsAdapter wordsAdapter;
    // 滚动监听器
    private RecyclerView.OnScrollListener scrollListener;
    // 弹出窗口视图
    private BasePopupView xPopup;
    // 输出字符串
    private String output = "";
    // 搜索建议词数组
    private JSONArray words;
    /**
     * 消息处理Handler
     * 处理搜索结果、歌曲详情跳转等异步操作
     */
    private final Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void dispatchMessage(@NonNull Message msg) {
            super.dispatchMessage(msg);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            FindMessageType findMessageType = FindMessageType.fromValue(msg.what);
            // 处理不同类型的消息
            switch (findMessageType) {
                case SONG_LIST_DATA: // 处理搜索结果
                    xPopup.smartDismiss(); // 关闭加载提示
                    if (msg.obj == null) { // 如果没有更多数据
                        songs.removeOnScrollListener(scrollListener); // 移除滚动监听
                    }
                    songsAdapter.setLoadMoreEnabled(false); // 禁用加载更多
                    songsAdapter.updateData((List<Song_Data>) msg.obj); // 更新歌曲列表

                    break;
                case SINGLE_SONG_DATA: // 处理单首歌曲搜索结果
                    xPopup.smartDismiss(); // 关闭加载提示
                    Song_Data song_data = (Song_Data) msg.obj;
                    Log.d("msg.obj", String.valueOf(msg.obj));
                    // 跳转到歌曲详情页面
                    startActivity(AboutSong.fromDataToIntent(getContext(), song_data));
                    break;
                case LOADING_ERROR: // 处理加载错误
                    Toast.makeText(getContext(), "加载错误\n原因：" + msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case SONG_NOT_EXIST: // 处理歌曲不存在的情况
                    Toast.makeText(getContext(), "歌曲不存在", Toast.LENGTH_SHORT).show();
                    break;
                case SEARCH_SUGGESTIONS: // 处理搜索建议词列表
                    words_recycler.setLayoutManager(new LinearLayoutManager(getContext()));
                    wordsAdapter = new WordsAdapter((JSONArray) msg.obj, getContext());
                    words_recycler.setAdapter(wordsAdapter);
                    break;
            }
        }
    };


    /**
     * Fragment创建时的回调
     */
    /**
     * Fragment创建时的回调
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    private boolean searchSongs(){
        searchBar.setText(searchView.getText());
        xPopup.dismiss();
        xPopup = new XPopup.Builder(getContext()).asLoading("正在加载中").show();
        songsAdapter.clearData();
        Songs = new ArrayList<>();
        String inputs = checkAndExtract(searchView.getText().toString());
        Log.d("inputs", searchView.getText().toString());
        // 判断是否是Key搜索模式
        if (extract(searchView.getText().toString())) {
            new Thread(() -> {
                Message message = new Message();
                try {
                    String output = Search.getsong(inputs, node);
                    Song_Data Song_Data = unmarshalSongData(output);
                    if (Song_Data == null) {
                        message.what = FindMessageType.SONG_NOT_EXIST.getValue();
                    } else {
                        message.what = FindMessageType.SINGLE_SONG_DATA.getValue();
                        message.obj = Song_Data;
                    }
                } catch (IOException e) {
                    Log.e("KEY搜歌", "错误原因", e);
                }
                mHandler.sendMessage(message);
            }).start();
        } else {
            String minNpsStr = minNps == 0.0? "": String.format("%.1f",minNps);
            String maxNpsStr = maxNps == MAX_NPS ? "" : String.format("%.1f",maxNps);
            search1 = new Search(searchView.getText().toString(), minNpsStr, maxNpsStr);
            SearchSongsInternal();
        }
        searchView.hide();
        return true;
    }

    AtomicBoolean isLoading = new AtomicBoolean(false);
    private synchronized void SearchSongsInternal(){
        if(isLoading.get())
            return;

        new Thread(() -> {
            isLoading.set(true);
            Message message = new Message();
            try {
                // SearchData(searchView.getText().toString(), minNpsStr, maxNpsStr);   //提交搜索数据
                String output = search1.GetSongPage(node);
                List<Song_Data> Song_Data = unmarshalSongDataList(output);
                message.what = FindMessageType.SONG_LIST_DATA.getValue();
                message.obj = Song_Data;
                isLoading.set(false);
            } catch (IOException e) {
                message.what = FindMessageType.LOADING_ERROR.getValue();
                message.obj = e;
                Log.e("搜索时出错", "错误信息为：", e);
            }
            mHandler.sendMessage(message);
        }).start();
    }

    /**
     * Fragment视图创建完成后的回调
     * 初始化视图组件和搜索功能
     */
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        InitView(view);
        initdata();
        initWords();
        // 设置搜索框的编辑完成监听器
        searchView.getEditText().setOnEditorActionListener((v, actionId, event) -> {
            return searchSongs();
        });

        scrollListener = new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if(dy == 0) // Ignore the initial layout.
                    return;

                int lastVisibleItemPosition = gridLayoutManager.findLastVisibleItemPosition();
                // 判断是否满足触发加载更多的条件
                if (lastVisibleItemPosition == songsAdapter.getItemCount() - 1) {
                    SearchSongsInternal();
                }
            }
        };
        songs.addOnScrollListener(scrollListener);
    }

    /**
     * 初始化搜索建议词列表
     * 从服务器获取热门搜索词并显示
     */
    private void initWords() {
        Message message = new Message();
        new Thread(() -> {
            words = Okhttp.GetWords();
            message.obj = words;
            message.what = FindMessageType.SEARCH_SUGGESTIONS.getValue();
            mHandler.sendMessage(message);
        }).start();
    }

    /**
     * 创建Fragment视图
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_find, container, false);

//        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//            @Override
//            public boolean onQueryTextSubmit(String query) {
//
//
//                return false;
//            }
//
//            @Override
//            public boolean onQueryTextChange(String newText) {
//                return false;
//            }
//        });


    }

    /**
     * 初始化歌曲数据
     * 加载默认的歌曲列表
     */
    private void initdata() {
        if (output.isEmpty()) {
            search1 = new Search("", "", "");
            xPopup = new XPopup.Builder(getContext()).asLoading("正在加载中");
            SearchSongsInternal();
        }
    }

    class NpsSeekBarChangeHandler implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            minNps = (float) (minNpsSeekBar.getProgress() / 10.0);
            maxNps = (float) (maxNpsSeekBar.getProgress() / 10.0);

            if (minNps > maxNps) {
                if (seekBar == minNpsSeekBar)
                {
                    maxNps = minNpsSeekBar.getProgress() + 1;
                    maxNpsSeekBar.setProgress((int) maxNps);
                }
                else if (seekBar == maxNpsSeekBar){
                    minNps = maxNpsSeekBar.getProgress() - 1;
                    minNpsSeekBar.setProgress((int) minNps);
                }
            }

            String maxNpsStr = maxNps * 10.0 >= MAX_NPS - 1 ? "∞" : String.format("%.1f", maxNps);
            npsText.setText(String.format("%.1f-%s", minNps, maxNpsStr));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    }

    private void setupAdvancedSearch(View rootView){

        minNpsSeekBar = rootView.findViewById(R.id.minNpsSeekBar);
        maxNpsSeekBar = rootView.findViewById(R.id.maxNpsSeekBar);
        npsText = rootView.findViewById(R.id.npsText);
//        searchBtn = rootView.findViewById(R.id.searchBtn);

        minNpsSeekBar.setMin(0);
        minNpsSeekBar.setMax(MAX_NPS);
        minNpsSeekBar.setProgress(0);

        maxNpsSeekBar.setMin(0);
        maxNpsSeekBar.setMax(MAX_NPS);
        maxNpsSeekBar.setProgress(MAX_NPS);

        minNpsSeekBar.setOnSeekBarChangeListener(new NpsSeekBarChangeHandler());
        maxNpsSeekBar.setOnSeekBarChangeListener(new NpsSeekBarChangeHandler());



//        searchBtn.setOnClickListener(v -> {
//            searchSongs();
//        });

    }

    /**
     * 初始化视图组件
     *
     * @param rootView Fragment的根视图
     */
    private void InitView(View rootView) {
        searchBar = rootView.findViewById(R.id.search_bar);
        searchView = rootView.findViewById(R.id.searchview);

        setupAdvancedSearch(rootView);

        words_recycler = rootView.findViewById(R.id.words_recycler);
        songs = rootView.findViewById(R.id.songs);
        node = SINGGAPORE_NODE;
        gridLayoutManager = new GridLayoutManager(this.getContext(), 2);
        songs.setLayoutManager(gridLayoutManager);
        songsAdapter = new SongsAdapter(Songs, getContext());
        songs.setAdapter(songsAdapter);
    }

}